﻿package net.wangit.view.chart.util;

import java.awt.Color;

public class ColorUtil {

	private static String codes[][] = { { "0", "0" }, { "1", "1" },
			{ "2", "2" }, { "3", "3" }, { "4", "4" }, { "5", "5" },
			{ "6", "6" }, { "7", "7" }, { "8", "8" }, { "9", "9" },
			{ "A", "10" }, { "B", "11" }, { "C", "12" }, { "D", "13" },
			{ "E", "14" }, { "F", "15" } };

	public ColorUtil() {
	}

	public static Color getColor(String hex) {
		int dec = 0;
		String hexColor = hex;
		if (hexColor == null)
			return new Color(dec);
		try {
			if (hexColor.trim().startsWith("#"))
				hexColor = hexColor.substring(1);
			String code = null;
			int length = hexColor.length();
			boolean isValid = false;
			for (int i = 0; i < length; i++) {
				code = hexColor.substring(i, i + 1);
				isValid = false;
				for (int j = 0; j < 16; j++) {
					if (code.compareToIgnoreCase(codes[j][0]) != 0)
						continue;
					dec += Integer.parseInt(codes[j][1])
							* power(length - i - 1);
					isValid = true;
					break;
				}

				if (!isValid)
					throw new IllegalArgumentException((new StringBuilder(
							"illegal hex color:")).append(hex).toString());
			}

		} catch (NumberFormatException e) {
			throw new IllegalArgumentException((new StringBuilder(
					"illegal hex color:")).append(hex).toString());
		}
		Color color = new Color(dec);
		return color;
	}

	private static int power(int exp) {
		int result = 1;
		for (int i = 0; i < exp; i++)
			result *= 16;

		return result;
	}

}
